home *** CD-ROM | disk | FTP | other *** search
- Path: pegasus.odyssee.net!news
- From: imaze@odyssee.net (Marc Mazerolle)
- Newsgroups: comp.lang.c++
- Subject: Re: C++ problem with constructor.
- Date: Thu, 21 Mar 1996 00:17:44 GMT
- Organization: Odyssee Internet
- Message-ID: <4iq74v$enb@pegasus.odyssee.net>
- References: <DoGGGp.Muy@latcs1.lat.oz.au>
- Reply-To: imaze@odyssee.net
- NNTP-Posting-Host: pool15_12.odyssee.net
- X-Newsreader: Forte Free Agent v0.55
-
- boylesgj@lion.cs.latrobe.edu.au (Gregary J Boyles) wrote:
-
- >See astericks
-
- >// main.cpp
-
- >#include <iostream.h>
- >#include "defines.h"
- >#include "address.h"
-
- >int main()
- >{
- > Address Address1(56,"Derby Drive","Epping",3165);
- > Address Address2(22,"Claremont Street","Fawkner",3060);
-
- > /********************************************************
- > After the above two calls Address1 and Address2 contain
- > all the appropriate data however after the next call all
- > 3 contain 0 or null strings. WHY?
- > ********************************************************/
-
- > Address Address3(Address1);
- > return(0);
- >}
-
-
-
- >// address.cpp
-
- >#include "address.h"
- >#include <string.h>
-
- >// Constructors
- >Address::Address(int ANumber,const char *AStreet,const char *ACity,int AZip)
- >{
- > Number=ANumber;
- > strcpy(Street,AStreet);
- > strcpy(City,ACity);
- > Zip=AZip;
- >}
-
- >Address::Address()
- >{
- > Number=0;
- > strcpy(Street,"");
- > strcpy(City,"");
- > Zip=0;
- >}
-
- >// Copy constructor
- >Address::Address(Address& AnAddress)
- >{
- > Number=AnAddress.Number;
- > strcpy(Street,AnAddress.Street);
- > strcpy(City,AnAddress.City);
- > Zip=AnAddress.Zip;
- >}
-
- >// Deconstructor
- >Address::~Address()
- >{
- > Number=0;
- > strcpy(Street,"");
- > strcpy(City,"");
- > Zip=0;
- >}
-
-
- >// address.h
-
- >#ifndef __ADDRESS_H
- >#define __ADDRESS_H
- >#define STR_STREET " street"
-
- >#include "defines.h"
-
- >class Address
- >{
- > private : int Number;
- > char *Street;
- > char *City;
- > int Zip;
-
- > public : // Constructors
- > Address(int ANumber,const char *AStreet,const char *ACity,int Zip);
- > Address();
- > // Copy constructor
- > Address(Address& AnAddress);
- > // Deconstructor
- > ~Address();
- >};
-
- >#endif
-
- When you declare "char *Street" in your class, you only declare a
- pointer, no space is reserved for the content of a string. Then you
- string-copy to this pointer (your lucky it does not bomb right there
- at your first copy). Before copying, you should allocate memory to the
- pointer like this :
-
- // Add 1 byte for the null at the end of string
- Street = new char[strlen(AStreet) + 1] ;
- // Then copy the string
- strcpy(Street,AStreet);
-
- In your destructor (not deconstructor) don't forget to free the memory
- allocated by "new" by doing :
-
- delete [] Street;
-
- Otherwise, after some times, you will run out of memory....
-
-